package com.totcy.atom.model;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.totcy.atom.CommonValues;
import com.totcy.atom.bean.ImagesBean;
import com.totcy.atom.presenter.contract.ImageGridContract;
import com.totcy.baselibrary.base.mvpbase.BaseModelImpl;
import com.totcy.baselibrary.httpcache.ACache;
import com.totcy.baselibrary.utils.NetUtil;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * description: xxxiao 分类数据 个人图片list model
 * author: Totcy
 * date: 2017/11/4 21:45
 * update: 2017/11/4
 */

public class ImageGridModel extends BaseModelImpl implements ImageGridContract.Model {


    private ACache aCache;
    private Gson gson = new Gson();

    public ImageGridModel(Context context) {
        super(context);
        aCache = ACache.get(context);
    }

    /**
     * 从网络获取数据
     *
     * @param url      链接
     * @param callback 回调presenter数据
     */
    @SuppressLint("CheckResult")
    @Override
    public void getImagesData(final String url, final DataCallback callback) {
        Observable.create(new ObservableOnSubscribe<List<ImagesBean>>() {
            @Override
            public void subscribe(ObservableEmitter<List<ImagesBean>> e) throws Exception {
                List<ImagesBean> imageListDomainList = new ArrayList<>();
                try {
                    Document document = Jsoup.connect(url).get();
                    Element content = document.getElementById("content");
                    Element article = content.getElementsByTag("article").first();
                    //图片
                    Element imgElement = article.getElementsByClass("post-content single-post-content").first();
                    String firstImgUrl = imgElement.select("img").first().attr("abs:src");

                    //分页节点
                    Element pageElement = article.getElementsByClass("paging").first();
                    //分页文字
                    String sizeStr = pageElement.select("span").first().text();

                    if (TextUtils.isEmpty(sizeStr)) {
                        return;
                    }
                    sizeStr = sizeStr.replace("页", "");
                    String sizeArr[] = sizeStr.split("/");
                    if (sizeArr.length < 2) {
                        return;
                    }
                    int imgSize = Integer.parseInt(sizeArr[1]);

                    for (int i = 1; i <= imgSize; i++) {
                        //http://img1.mm131.me/pic/1619/1.jpg
                        int lastSplit = firstImgUrl.lastIndexOf("/");
                        String url1 = firstImgUrl.substring(0,lastSplit);
                        String url2 = firstImgUrl.substring(lastSplit,firstImgUrl.length());

                        String imgTab[] =  url2.split("\\.");
                        if(imgTab.length < 2){
                            return;
                        }

                        String imageUrl = url1 + "/" + i + "." + imgTab[1];

                        //构建一个图片实体
                        ImagesBean bean = new ImagesBean();
                        bean.setUrl(imageUrl);
                        bean.setThumbnailUrl(imageUrl);
                        imageListDomainList.add(bean);
                        if (CommonValues.isRunningTest)
                            Log.d("Tag", "imageUrl =" + imageUrl );
                    }

                    e.onNext(imageListDomainList);

                } catch (IOException exception) {
                    e.onError(exception);
                }
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<ImagesBean>>() {
                               @Override
                               public void accept(@NonNull List<ImagesBean> girlBeen) throws Exception {
                                   callback.onDataSuccess(girlBeen);
                                   aCache.put(url, gson.toJson(girlBeen));
                               }
                           }, new Consumer<Throwable>() {
                               @Override
                               public void accept(@NonNull Throwable throwable) throws Exception {
                                   if (!NetUtil.isConnected(mContext)) {
                                       String json = aCache.getAsString(url);
                                       if (!TextUtils.isEmpty(json)) {
                                           List<ImagesBean> images = gson.fromJson(
                                                   json,
                                                   new TypeToken<List<ImagesBean>>() {
                                                   }.getType()
                                           );
                                           callback.onDataSuccess(images);
                                       }
                                   }
                                   callback.onDataNotAvailable();
                                   if (CommonValues.isRunningTest)
                                       Log.e("ImageListModel", "onError: " + throwable.getMessage());
                               }
                           }
                );

    }

    @Override
    public void canCelRequest() {
    }


}